package com.yy.controller.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yy.context.BaseContext;
import com.yy.controller.mapper.AddressBookMapper;
import com.yy.controller.mapper.OrderDetailMapper;
import com.yy.controller.mapper.OrderMapper;
import com.yy.controller.mapper.ShoppingCartMapper;
import com.yy.controller.service.OrderService;
import com.yy.dto.OrderPageQueryDTO;
import com.yy.entity.AddressBook;
import com.yy.entity.OrderDetail;
import com.yy.entity.Orders;
import com.yy.entity.ShoppingCart;
import com.yy.result.PageResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 条件分页查询订单列表
     *
     * @return
     */
    @Override
    public PageResult list(OrderPageQueryDTO orderPageQueryDTO) {
        if (orderPageQueryDTO.getEndTime() != null) {
            LocalDateTime endTime = orderPageQueryDTO.getEndTime().plusSeconds(23 * 60 * 60 + 59 * 60 + 59);
            orderPageQueryDTO.setEndTime(endTime);
        }
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.list(orderPageQueryDTO);
        for (Orders orders : page.getResult()) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getListByOrderId(orders.getId());
            orders.setOrderDetailList(orderDetailList);
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 查询所有订单信息
     *
     * @return
     */
    @Override
    public List<Orders> AllOrder() {
        List<Orders> ordersList = orderMapper.AllOrder();
        return ordersList;
    }

    /**
     * 修改订单状态(若为取消,添加取消原因)
     *
     * @param id
     * @param cancelReason
     */
    @Override
    public void updateStatus(Long id, String cancelReason) {
        if (!cancelReason.equals("undefined")) {
            if(cancelReason.equals("null")){
                cancelReason="";
            }
            LocalDateTime cancelTime = LocalDateTime.now();
            orderMapper.upDateStatusAndReason(id, cancelReason, cancelTime);
        } else {
            //获取订单状态
            Integer status = orderMapper.statusById(id);
            LocalDateTime deliveryTime = LocalDateTime.now();
            if (status != 4) {
                deliveryTime = null;
            }
            orderMapper.upDateStatus(id, deliveryTime);
        }
    }

    /**
     * 创建订单
     *
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public Long create(Orders orders) {
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String text = orders.getText();
        String time = orders.getTime();
        // 获取年、月、日
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        int day = currentDate.getDayOfMonth();
        if (text != null || text != "") {
            if (time.length() > 5) {
                time = time.substring(time.indexOf("(") + 1, time.indexOf(")"));
            }
        } else {
            if (text == "明天") {
                day = day + 1;
            }
            if (text == "后天") {
                day = day + 2;
            }
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm");
        LocalTime t = LocalTime.parse(time, formatter);

        // 创建 LocalDate 对象
        LocalDate date = LocalDate.of(year, month, day);

        // 创建 LocalDateTime 对象
        LocalDateTime dateTime = LocalDateTime.of(date, t);


        orders.setEstimatedDeliveryTime(dateTime);
        orders.setNumber(Long.toString(System.currentTimeMillis()));

        orders.setOrderTime(LocalDateTime.now());

        orders.setAddressBookId(orders.getAddressBookId());
        orders.setStatus(1);


        //查购物车
        BigDecimal amount = BigDecimal.valueOf(0.00);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(userId);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BigDecimal a = shoppingCart.getAmount();
            amount = amount.add(a);
        }
        orders.setAmount(amount.add(BigDecimal.valueOf(4)));
        //添加订单
        orderMapper.add(orders);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            shoppingCart.setOrderId(orders.getId());
            //添加到订单明细
            orderDetailMapper.add(shoppingCart);
        }
        //清空购物车信息
        shoppingCartMapper.clear(userId);
        return orders.getId();
    }

    /**
     * 获取订单信息及详情
     *
     * @param id
     * @return
     */
    @Override
    public Orders getOne(Long id) {
        Orders orders = orderMapper.getByid(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getListByOrderId(id);
        orders.setOrderDetailList(orderDetailList);
        return orders;
    }

    /**
     * 超时取消订单
     *
     * @param id
     */
    @Override
    public void overtimeCancel(Long id) {

        orderMapper.upDateStatusAndReason(id,
                "订单超时,自动取消!",
                LocalDateTime.now());
    }

    /**
     * 根据用户id获取订单列表
     *
     * @return
     */
    @Override
    public List<Orders> getListByUserId() {
        Long userId = BaseContext.getCurrentId();
        List<Orders> ordersList = orderMapper.getListByUserId(userId);
        for (Orders orders : ordersList) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getListByOrderId(orders.getId());
            orders.setOrderDetailList(orderDetailList);
        }
        return ordersList;
    }

    /**
     * 支付成功
     *
     * @param id
     */
    @Override
    public void paySuccess(Long id, Integer payMethod) {
        Orders orders = orderMapper.getByid(id);
        orders.setStatus(2);
        orders.setPayMethod(payMethod);
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.paySucess(orders);
    }

    /**
     * 用户取消订单
     *
     * @param id
     * @param cancelReason
     */
    @Override
    public void userCancel(Long id, String cancelReason) {
        Long userId = BaseContext.getCurrentId();
        LocalDateTime cancelTime = LocalDateTime.now();
        orderMapper.userCancel(id,cancelReason,cancelTime,userId);

    }
}

